﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class CommonFunctionA : MonoBehaviour {

	// Use this for initialization
    //private bool m_bIsActive=false,m_bIsFixBG=false;
    private int m_iFixAction, m_iType;
    private Vector3 m_vAction;
    private GameObject m_gMover,m_pBorder,m_gDeleteFireBall;
    private float m_fTime,m_fTimePass,m_fCamera,m_fCameraEnd,m_fCameraV,m_fCameraDir;
    private Vector3 m_vEnd,m_vStart;
    //private Transform m_tStairs, m_tBackGround;
    public List<GameObject> m_lstFireBall;
    public static GameObject m_gSelf;
    private Slider m_slSkill;
    public static bool m_bIsRestart,m_bIsChangeScene;

    private bool m_bIsPauseBtnPress, m_bIsPauseMusicBtnPress;//用来响应游戏界面暂停游戏、暂停音乐

    public void ChangeCameraScene(float fBeg, float fEnd, float fV)
    {
        m_bIsChangeScene = true;
        m_fCamera = fBeg;
        m_fCameraV = fV;
        m_fCameraEnd = fEnd;
        if (fBeg > fEnd) m_fCameraDir = -1;
        else m_fCameraDir = 1;
    }

    public static void PlayJumpAudio(GameObject gStair,GameObject gPlayer)
    {
        //根据之前跳的stair类型，决定跳的声音
        if (initial.m_bIsPauseMusicBtnPress) return;
        
        int iType=gStair.GetComponent<StairProperty>().m_iType;
        //CommonFunctionA.logger("iType:" + iType, 1);
        switch (iType)
        {
            case 1:
                //普通
                PlayAudio(gPlayer, "jump1");
                //CommonFunctionA.logger("111111111", 1);
                break;

            case 2:
                if(gStair.GetComponent<StairProperty>().m_iType2==1)
                    PlayAudio(gPlayer, "jump3");
                else if (gStair.GetComponent<StairProperty>().m_iType2 == 2)
                    PlayAudio(gPlayer, "jump4");
                break;

            case 3:
                PlayAudio(gPlayer, "jump2");
                break;

            case 4:
                PlayAudio(gPlayer, "jump5");
                break;

            case 5:
                PlayAudio(gPlayer, "jump6");
                break;
        }
    }

    public static void InitialAudio()
    {
        Hashtable ht = GameData.htAudio = new Hashtable();
        /*
        ht.Add("GameFBM_00", (AudioClip)Resources.Load("Sounds/GameFBM_00", typeof(AudioClip)));
        ht.Add("GameFBM_01", (AudioClip)Resources.Load("Sounds/GameFBM_01", typeof(AudioClip)));
        ht.Add("jump1", (AudioClip)Resources.Load("Sounds/jump1", typeof(AudioClip)));
        ht.Add("jump2", (AudioClip)Resources.Load("Sounds/jump2", typeof(AudioClip)));
        ht.Add("jumpDead", (AudioClip)Resources.Load("Sounds/jumpDead", typeof(AudioClip)));
        ht.Add("GameBGM_00", (AudioClip)Resources.Load("Sounds/GameBGM_00", typeof(AudioClip)));
        ht.Add("GameBGM_01", (AudioClip)Resources.Load("Sounds/GameBGM_01", typeof(AudioClip)));
        ht.Add("GameBirdSound_00", (AudioClip)Resources.Load("Sounds/GameBirdSound_00", typeof(AudioClip)));
        ht.Add("GameBirdSound_01", (AudioClip)Resources.Load("Sounds/GameBirdSound_01", typeof(AudioClip)));
        ht.Add("StartMain", (AudioClip)Resources.Load("Sounds/StartMain", typeof(AudioClip)));
        ht.Add("ready", (AudioClip)Resources.Load("Sounds/ready", typeof(AudioClip)));
        ht.Add("jump3", (AudioClip)Resources.Load("Sounds/jump3", typeof(AudioClip)));
        ht.Add("jump4", (AudioClip)Resources.Load("Sounds/jump4", typeof(AudioClip)));
        ht.Add("jump5", (AudioClip)Resources.Load("Sounds/jump5", typeof(AudioClip)));
        ht.Add("jump6", (AudioClip)Resources.Load("Sounds/jump6", typeof(AudioClip)));
        ht.Add("fail", (AudioClip)Resources.Load("Sounds/fail", typeof(AudioClip)));
        ht.Add("enegyAbsorb", (AudioClip)Resources.Load("Sounds/enegyAbsorb", typeof(AudioClip)));*/

        ht.Add("StartMain", (AudioClip)Resources.Load("Sounds/StartMain", typeof(AudioClip)));
        ht.Add("enegyAbsorb", (AudioClip)Resources.Load("Sounds/enegyAbsorb", typeof(AudioClip)));
        ht.Add("fail", (AudioClip)Resources.Load("Sounds/fail", typeof(AudioClip)));
        ht.Add("GameBGM_00", (AudioClip)Resources.Load("Sounds/GameBGM_00", typeof(AudioClip)));
        ht.Add("GameBGM_01", (AudioClip)Resources.Load("Sounds/GameBGM_01", typeof(AudioClip)));
        ht.Add("GameBGM_02", (AudioClip)Resources.Load("Sounds/GameBGM_02", typeof(AudioClip)));
        ht.Add("GameBGM_03", (AudioClip)Resources.Load("Sounds/GameBGM_03", typeof(AudioClip)));
        ht.Add("GameBGM_04", (AudioClip)Resources.Load("Sounds/GameBGM_04", typeof(AudioClip)));
        ht.Add("GameBirdSound_00", (AudioClip)Resources.Load("Sounds/GameBirdSound_00", typeof(AudioClip)));
        ht.Add("GameBirdSound_01", (AudioClip)Resources.Load("Sounds/GameBirdSound_01", typeof(AudioClip)));
        ht.Add("GameBirdSound_02", (AudioClip)Resources.Load("Sounds/GameBirdSound_02", typeof(AudioClip)));
        ht.Add("GameBirdSound_03", (AudioClip)Resources.Load("Sounds/GameBirdSound_03", typeof(AudioClip)));
        ht.Add("GameBirdSound_04", (AudioClip)Resources.Load("Sounds/GameBirdSound_04", typeof(AudioClip)));
        ht.Add("GameFBM_00", (AudioClip)Resources.Load("Sounds/GameFBM_00", typeof(AudioClip)));
        ht.Add("GameFBM_01", (AudioClip)Resources.Load("Sounds/GameFBM_01", typeof(AudioClip)));
        ht.Add("GameFBM_02", (AudioClip)Resources.Load("Sounds/GameFBM_02", typeof(AudioClip)));
        ht.Add("GameFBM_03", (AudioClip)Resources.Load("Sounds/GameFBM_03", typeof(AudioClip)));
        ht.Add("GameFBM_04", (AudioClip)Resources.Load("Sounds/GameFBM_04", typeof(AudioClip)));
        ht.Add("jump1", (AudioClip)Resources.Load("Sounds/jump1", typeof(AudioClip)));
        ht.Add("jump2", (AudioClip)Resources.Load("Sounds/jump2", typeof(AudioClip)));
        ht.Add("jump3", (AudioClip)Resources.Load("Sounds/jump3", typeof(AudioClip)));
        ht.Add("jump4", (AudioClip)Resources.Load("Sounds/jump4", typeof(AudioClip)));
        ht.Add("jump5", (AudioClip)Resources.Load("Sounds/jump5", typeof(AudioClip)));
        ht.Add("jump6", (AudioClip)Resources.Load("Sounds/jump6", typeof(AudioClip)));
        ht.Add("jumpDead", (AudioClip)Resources.Load("Sounds/jumpDead", typeof(AudioClip)));
        ht.Add("ready", (AudioClip)Resources.Load("Sounds/ready", typeof(AudioClip)));
        ht.Add("Skill_2", (AudioClip)Resources.Load("Sounds/Skill_2", typeof(AudioClip)));
        ht.Add("Skill_3", (AudioClip)Resources.Load("Sounds/Skill_3", typeof(AudioClip)));
    }

    public static void StopAudio(GameObject g)
    {
        AudioSource source = (AudioSource)g.GetComponent("AudioSource");
        source.Stop();
    }

    public static void PlayAudio(GameObject g, string s)
    {
        if (initial.m_bIsPauseMusicBtnPress) return;
        //logger("-->>>" + s, 1);
        AudioClip clip = (AudioClip)GameData.htAudio[s];
        
        if (clip == null)
        {
            //logger("11111", 1);
            return;
        }
        //logger("22222", 1);
        AudioSource source = (AudioSource)g.GetComponent("AudioSource");
        if (source == null)
            source = (AudioSource)g.AddComponent<AudioSource>();
        source.clip = clip;
        //CommonFunctionA.logger("clip:" + clip.name, 1);
        source.minDistance = 1.0f;
        source.maxDistance = 50;
        source.rolloffMode = AudioRolloffMode.Linear;
        //Debug.Log("3333");
        source.Play();
    }

    public static void PauseAudio(GameObject g)
    {
        //logger("现在在暂停音乐", 1);
        AudioSource source = (AudioSource)g.GetComponent("AudioSource");
        source.Pause();
    }

    public static void RePlayAudio(GameObject g)
    {
        //logger("现在在重播音乐", 1);
        AudioSource source = (AudioSource)g.GetComponent("AudioSource");
        source.Play();
    }

    public static void logger(object message, int t)
    {
        string s = "[" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + "]" + message.ToString();
        switch (t)
        {
            case 1:
                Debug.Log(s);
                break;
            case 2:
                Debug.LogWarning(s);
                break;
        }
    }

    public static Sprite SetSpriteTexture(Texture2D t2d)
    {
        Sprite sp = Sprite.Create(t2d, new Rect(0, 0, t2d.width, t2d.height), new Vector2(0.5f, 0.5f));
        return sp;
    }


    public static Texture2D loadPicture(string path)
    {
        Texture2D t2d = (Texture2D)Resources.Load(path);
        if (t2d == null)
        {
            //说明本地没有图，以默认代替
            t2d = (Texture2D)Resources.Load("default");
        }
        return t2d;
    }

    public static void ChangeCameraSizeTamplate(GameObject g, float fFrom, float fTo, float fChangeV)
    {
        CommonMove cm = g.GetComponent<CommonMove>();
        if (cm == null)
        {
            cm = Camera.main.gameObject.AddComponent<CommonMove>();
        }
        cm.ChangeCameraSize(fFrom, fTo, fChangeV);
    }

    public static void MoveObjectTamplate(GameObject g, Vector3 vFrom, Vector3 vTo, int iType, float fCostTime,string sCallBackFunction = null)
    {
        CommonMove cm = g.GetComponent<CommonMove>();
        if (cm == null)
        {
            cm = Camera.main.gameObject.AddComponent<CommonMove>();
        }
        cm.MoveObject(vFrom, vTo, iType, fCostTime,sCallBackFunction);
    }

    public static void ShowFontTamplate(GameObject g,float fStartFont, float fEndFont,float fV)
    {
        CommonMove cm = g.GetComponent<CommonMove>();
        if (cm == null)
        {
            cm = g.AddComponent<CommonMove>();
        }
        cm.ShowTexture(fStartFont, fEndFont, fV);
    }

    public static void ShowWindowsTamplate(GameObject g, float fStartFont, float fEndFont, float fV)
    {
        CommonMove cm = g.GetComponent<CommonMove>();
        if (cm == null)
        {
            cm = g.AddComponent<CommonMove>();
        }
        cm.ShowTexture(fStartFont, fEndFont, fV);
    }

    public void onBtnEvent(GameObject btn, UserOperate.btnState btnState)
    {
        if (btnState == UserOperate.btnState.btnStateUp && btn.name == "btnRestart")
        {
            //当游戏失败时，响应重新玩的按钮。
            UnityEngine.SceneManagement.SceneManager.LoadScene("Loading");
        }
        else if (btnState == UserOperate.btnState.btnStateUp && btn.name == "btnExit")
        {
            //游戏失败时、开始界面时的退出游戏
            Application.Quit();
        }
        else if (btnState == UserOperate.btnState.btnStateUp && btn.name == "GameMain_Back")
        {
            //当正在游戏时，点击后退按钮。
            Debug.Log("游戏中点退出");
            
            UnityEngine.SceneManagement.SceneManager.LoadScene("Start");
        }
        else if (btnState == UserOperate.btnState.btnStateUp && btn.name == "GameMain_Pause")
        {
            //当正在游戏时，点击暂停游戏
            if (m_bIsPauseBtnPress)
            {
                //说明暂停之前已被按下，那么这里应该是继续游戏，将图标换成暂停
                m_bIsPauseBtnPress = false;
                GameData.gi.bIsGameRunning = true;
                btn.GetComponent<Image>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("stop"));
            }
            else
            {
                //说明暂停之前未被按下，那么这里应该是暂停游戏，将图标换成运行
                m_bIsPauseBtnPress = true;
                GameData.gi.bIsGameRunning = false;
                btn.GetComponent<Image>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("play"));
            }

        }
        else if (btnState == UserOperate.btnState.btnStateUp && btn.name == "GameMain_Sound")
        {
            //当正在游戏时，点击关闭声音
            if (m_bIsPauseMusicBtnPress)
            {
                //说明暂停音乐之前已被按下，那么这里应该是去掉划杆，并播音乐
                m_bIsPauseMusicBtnPress = false;
                RePlayAudio(btn.gameObject);
                btn.GetComponent<Image>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("sound"));
            }
            else
            {

                //说明暂停音乐之前未被按下，那么这里应该是加上划杆，并停播音乐
                m_bIsPauseMusicBtnPress = true;
                PauseAudio(btn.gameObject);
                btn.GetComponent<Image>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("NoSound"));
            }
        }
        else if (btnState == UserOperate.btnState.btnStateUp && btn.name == "btnQuestion")
        {
            //当游戏中，碰到问题弹出框时，点击确定
            btn.transform.parent.gameObject.GetComponent<MessageBox>().onClick();
        }
        else if (btnState == UserOperate.btnState.btnStateUp && btn.name == "StartMain_btnBack")
        {
            //当在选角色界面点击退后。
            btn.transform.parent.gameObject.SetActive(false);
        }
        else if (btnState == UserOperate.btnState.btnStateUp && btn.name == "btnInfo")
        {
            //当在开始界面选择帮助
            UnityEngine.SceneManagement.SceneManager.LoadScene("Help");
        }
        
        if (btnState == UserOperate.btnState.btnStateUp && btn.name == "btnSkill")
        {
            //当在开始界面选择帮助
            Transform tPlayer = GameData.pi.gPlayer.transform;
            Transform tSkill=null;
            m_bIsRestart = false;
            for (int i = 0; i < tPlayer.childCount; i++)
            {
                if (tPlayer.GetChild(i).name == "Border")
                {
                    tPlayer.GetChild(i).gameObject.SetActive(true);
                    tSkill = tPlayer.GetChild(i);
                }
            }
            if (GameData.pi.iChar == 0)
            {
                //第一个角色，能量积满是增加生命值
                //btn.transform.GetChild(0).GetComponent<RawImage>().texture = CommonFunctionA.loadPicture("Skill_1");
                btn.gameObject.SetActive(false);
                GameData.pi.iLife++;
                //tSkill.GetComponent<SpriteRenderer>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("SkillBorder"));
                StartCoroutine(SkillOver(1, 0));
            }
            else if (GameData.pi.iChar == 1)
            {
                //第二个角色，能减速
                //btn.transform.GetChild(0).GetComponent<RawImage>().texture = CommonFunctionA.loadPicture("Skill_2");
                btn.gameObject.SetActive(false);
                //tSkill.GetComponent<SpriteRenderer>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("SkillBorder"));
                StartCoroutine(SkillOver(10, 1));
                GameData.gi.fGameSpeed = 0.5f;
            }

            else if (GameData.pi.iChar == 2)
            {
                //第三个角色，能无敌
                //btn.transform.GetChild(0).GetComponent<RawImage>().texture = CommonFunctionA.loadPicture("Skill_3");
                btn.gameObject.SetActive(false);
                tSkill.GetComponent<SpriteRenderer>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("SkillBorder"));
                StartCoroutine(SkillOver(15, 2));
                GameData.pi.iPlayerStatus = 1;
            }
            else if (GameData.pi.iChar == 3)
            {
                //第三个角色，能无敌
                //btn.transform.GetChild(0).GetComponent<RawImage>().texture = CommonFunctionA.loadPicture("Skill_4");
                btn.gameObject.SetActive(false);
                tSkill.GetComponent<SpriteRenderer>().sprite = CommonFunctionA.SetSpriteTexture(CommonFunctionA.loadPicture("wing"));
                StartCoroutine(SkillOver(15, 3));
                GameData.pi.iPlayerStatus = 2;
            }
            GameData.pi.iEnegyNum = 0;
            NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_RefreshInterface", null);
        }
    }
        

    IEnumerator SkillOver(float time,int iType)
    {
        yield return new WaitForSeconds(time);
        if (!m_bIsRestart)
        {
            Transform tPlayer = GameData.pi.gPlayer.transform;
            for (int i = 0; i < tPlayer.childCount; i++)
            {
                if (tPlayer.GetChild(i).name == "Border")
                {
                    tPlayer.GetChild(i).gameObject.SetActive(false);
                }
            }
            if (iType == 0)
            {
                //第1角色，加血
            }
            else if (iType == 1)
            {
                //第2角色，恢复速度
                GameData.gi.fGameSpeed = 1f;
            }
            else if (iType == 2)
            {
                //第3角色，恢复无敌
                GameData.pi.iPlayerStatus = 0;
            }
            else if (iType == 3)
            {
                //第4角色，飞行
                //如果还在HIDE上面，就输了。
                if (GameData.pi.gPlayer.GetComponent<PlayerScript>().m_gCurStair.name == "stair_hide")
                {
                    NotificationCenter.DefaultCenter().PostNotification(this, "GameMain_GameOver", null);
                }
                GameData.pi.iPlayerStatus = 0;
            }
        }
    }

    public void onDropEvent(GameObject obj, UserOperate.dragState btnState, PointerEventData eventData)
    {
    }

    public void addListening()
    {
        EventDispatcher.btnEvent += onBtnEvent;
        EventDispatcher.dropEvent += onDropEvent;		
    }

    public void initialListener()
    {
        EventDispatcher.CleanListener();
        addListening();
    }

    private static CommonFunctionA initial;
    public static CommonFunctionA Initial()
    {
        if (!initial)
        {
            GameObject commonFunction = new GameObject("CommonFunctionA");
            m_gSelf = commonFunction;
            initial = commonFunction.AddComponent<CommonFunctionA>();
            DontDestroyOnLoad(commonFunction);
            InitialAudio();
        }
        return initial;
    }

	void Start () {
        addListening();
        m_lstFireBall = new List<GameObject>();
        NotificationCenter.DefaultCenter().AddObserver(this, "CommonFunctionA_AddObject");
        m_bIsPauseBtnPress = false; 
        m_bIsPauseMusicBtnPress = false;
	}

    public void CommonFunctionA_AddObject(Notification n)
    {
        Hashtable adata = (Hashtable)n.data;
        GameObject g=adata["msg"] as GameObject;
        m_lstFireBall.Add(g);
    }

    
	
	// Update is called once per frame
	void Update () {

        if (m_bIsChangeScene)
        {
            m_fCamera = m_fCamera + (m_fCameraDir * Time.deltaTime * m_fCameraV);
            Camera.main.GetComponent<Effect>().ma.SetFloat("_Float1", m_fCamera);
            if (m_fCameraDir < 0)
            {
                if (m_fCamera < m_fCameraEnd)
                {
                    m_bIsChangeScene = false;
                }                
            }
            else if (m_fCameraDir > 0)
            {
                if (m_fCamera > m_fCameraEnd)
                {
                    m_bIsChangeScene = false;
                }
            }
        }
        /*
        if (GameData.gi.bIsGameRunning)
        {
            //火球
            int iCount=m_lstFireBall.Count;
            for (int i = 0; i < iCount; i++)
            {
                if (m_lstFireBall[i] == null)
                {
                    m_lstFireBall.Remove(m_lstFireBall[i]);
                    i--;
                    iCount--;
                    continue;
                }

                if (m_lstFireBall[i].name == "FireBall")
                {
                    m_lstFireBall[i].transform.Translate(0, -5 * Time.deltaTime, 0);
                }
                else if (m_lstFireBall[i].name == "FireBall_Follow")
                {
                    //生成一个附近位置
                    //Vector3 vPlayer = GameData.GetInstance().gPlayer.transform.position;
                    //vPlayer = new Vector3(vPlayer.x + UnityEngine.Random.Range(-2f, 2f), vPlayer.y + UnityEngine.Random.Range(-2f, 2f), 0);
                    //Vector3 vAction = vPlayer - m_lstFireBall[i].transform.position;
                    Vector3 v = new Vector3(UnityEngine.Random.Range(-0.5f,0.5f), -1, 0);
                    m_lstFireBall[i].transform.Translate(5*Time.deltaTime*v);
                }
            }
        }
         */
        /*
        if (m_bIsActive)
        {
            //前0.5秒和后0.5秒慢速
            
            Vector3 vStep = m_vAction * Time.deltaTime / m_fTime;
            m_fTimePass += Time.deltaTime;
            if (m_fTimePass <= 1)
            {
                vStep *= m_fTimePass * m_fTimePass;
            }  
            else if(m_fTimePass >= m_fTime)
            {
                vStep *= (m_fTimePass - m_fTime-1) * (m_fTimePass - m_fTime-1);
            }
            m_gMover.transform.Translate(vStep);
            if (Vector3.Distance(m_gMover.transform.position, m_vEnd) < 1)
            {
                m_bIsActive = false;
                if (m_iType == 1)
                {
                    MoveObject(Camera.main.gameObject, m_vEnd, m_vStart, 5, 2);
                    FixBackGround(m_tStairs, m_tBackGround, 2);
                }
                else if (m_iType == 2)
                {
                    FixBackGround(m_tStairs, m_tBackGround, 1);
                }
            }
        }
    */
	}

    public void MessageBox(GameObject gBorder, MsgBox MBquestion)
    {
        gBorder.SetActive(true);
        gBorder.GetComponent<MessageBox>().m_MBquestion = MBquestion;
        UnityEngine.UI.Text[] ts = gBorder.GetComponentsInChildren<UnityEngine.UI.Text>();
        for (int i = 0; i < ts.Length; i++)
        {
            if (ts[i].name == "Title")
            {
                ts[i].text = MBquestion.sTitle;
            }
            else if (ts[i].name == "Content")
            {
                ts[i].text = MBquestion.sContent;
            }
        }
    }
    /*
    public void MoveObject(GameObject g, Vector3 vStart, Vector3 vEnd, float fTime, int iType)
    {
        //删除了，无用
        //iType 1向上 2向下
        m_vAction = vEnd - vStart;
        m_vEnd = vEnd;
        m_vStart = vStart;
        //GameData.logger("vEnd:" + vEnd + ",vStart:" + vStart, 1);
        Camera.main.transform.position = vStart;
        //Camera.main.transform.position = new Vector3(0,vStart.y,Camera.main.transform.position.z);
        m_gMover = g;
        m_fTime = fTime;
        m_fTimePass = 0;
        m_bIsActive = true;
        m_iType = iType;
        
    }
    */
}

